跳到主要内容

Linux 的 Shell

当前使用的 Shell

打印 /etc/shells 这个文件,检查当前 Linux 有多少可用的 Shells

$ cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/usr/bin/bash
/bin/rbash
/usr/bin/rbash
/bin/dash
/usr/bin/dash
/usr/bin/tmux
/usr/bin/screen
/bin/zsh
/usr/bin/zsh

这里只介绍比较常用的两个个

/bin/sh (已经被 /bin/bash 所取代)
/bin/bash (就是 Linux 默认的 shell)

其中的 /bin/bash 是 Linux 默认的 Shell

设置默认的 Bash

# 查看当前使用的 Shell
echo $SHELL

chsh -s /bin/bash

该命令将更改当前用户的默认 Shell 为 Bash。执行该命令后,需要重新登录用户才能生效。

历史命令

bash 会把当前使用过的命令记录下来,保存在 .bash_history 里面

需要留意的是,~/.bash_history 记录的是前一次登陆以前所执行过的指令, 而至于这一次登陆所执行的指令都被暂存在内存中,当登出系统后,该指令记忆才会记录到 .bash_history 当中

可以使用 history 命令检查历史命令

$ history
...
780 cat ~/.bash_history
781 cat ~/.zsh_history
782 cat /etc/shells
783 type cd
784 type go
785 env
786 set
787 echo $$

这个 history 命令除了可以查看命令,还可以搭配 ! 一起使用

$ !number
$ !command
$ !!

number :执行第几笔指令的意思; command :由最近的指令向前搜寻“指令串开头为 command”的那个指令,并执行; !! :就是执行上一个指令(相当于按↑按键后,按 Enter)

e.g.

$ history
66 man rm
67 alias
68 man history
69 history
..

$ !66 # 执行第 66 个指令
$ !! # 执行上一个指令,本例中亦即 !66
$ !al # 执行最近以 al 为开头的指令(上头列出的第 67 个)

设置别名

alias lm='ls -al'

# 去掉别名
unalias lm

查询指令类型

查询指令是否为 Bash shell 的内置命令

bash 已经“内置”了很多指令了,那如何知道这个命令是否是 bash 的内置命令呢?

利用 type 这个指令来观察即可

type [-tpa] name
选项与参数:
:不加任何选项与参数时,type 会显示出 name 是外部指令还是 bash 内置指令
-t :当加入 -t 参数时,type 会将 name 以下面这些字眼显示出他的意义:
file :表示为外部指令;
alias :表示该指令为命令别名所设置的名称;
builtin :表示该指令为 bash 内置的指令功能;
-p :如果后面接的 name 为外部指令时,才会显示完整文件名;
-a :会由 PATH 变量定义的路径中,将所有含 name 的指令都列出来,包含 alias

e.g.

$ type cd
cd is a shell builtin

$ type go
go is /usr/bin/go

bash 的欢迎讯息

经常看到别人进入 Shell 之后,开头有段欢迎信息,这个如何设置呢?

/etc/issue 里面设置

$ cat /etc/issue
Ubuntu 20.04.3 LTS \n \l
issue 内的各代码意义
\d 本地端时间的日期;
\l 显示第几个终端机接口;
\m 显示硬件的等级 (i386/i486/i586/i686...);
\n 显示主机的网络名称;
\O 显示 domain name;
\r 操作系统的版本 (相当于 uname -r)
\t 显示本地端时间的时间;
\S 操作系统的名称;
\v 操作系统的版本。

References

10.2 Shell 的变量功能